import { Key, useRef, useState } from 'react';
import { GCrudTable, GFormSchema, GIcon } from 'geminis-react';
import { Button, Divider } from 'antd';
import styles from './components/tree.less';
import { CagegoryTree } from '@/pages/everydata/category/components/tree';

export default () => {
  const table = useRef<any>();
  const tree = useRef<any>();
  const [selection, setSelection] = useState({
    selectedRows: [],
  });

  const onTreeSelect = (selectedKeys: Key[]) => {
    table.current.loadData({
      filters: [
        {
          field: 'parentId',
          compareType: selectedKeys[0] === '' ? 'is null' : '=',
          value: selectedKeys[0],
        },
      ],
    });
  };

  const reloadData = (value: any, resp?: any) => {
    tree.current.reloadSelectedNode();
    table.current.loadData();
  };

  const schema = {
    title: '分类信息',
    table: {
      schema: {
        data: {
          autoload: false,
          url: '/api/everydata/categories',
        },
      },
      schemaPath: '/everydata-pc/schemas/category/table.json',
      onDeleted: reloadData,
    },
    add: {
      form: {
        schema: {
          data: {
            url: '/api/everydata/categories',
          },
        },
        schemaPath: '/everydata-pc/schemas/category/edit.json',
        onSubmitting: (schema: GFormSchema, value: any) => {
          const parentId = tree.current.selection.selectedKeys[0];
          value.parentId = parentId === '' ? null : parentId;
          value.parentPath =
            tree.current.selection.selectedNodes[0].data.pathId;
          return value;
        },
        onSubmitted: reloadData,
      },
    },
    delete: false,
  };

  return (
    <div className={styles.main}>
      <div className={styles.tree}>
        <CagegoryTree ref={tree} showRoot={true} onSelect={onTreeSelect} />
      </div>
      <Divider type="vertical" className={styles.fullHeight} />
      <div className={styles.content}>
        <GCrudTable
          ref={table}
          schema={schema}
          onSelected={(value: any) => setSelection(value)}
          external={{
            pos3: (
              <Button
                icon={<GIcon type="icon-delete" />}
                disabled={selection.selectedRows.length === 0}
                onClick={() => {
                  table.current?.deleteData(
                    selection.selectedRows.map((row: any) => row.pathId),
                  );
                }}
              >
                删除
              </Button>
            ),
          }}
        />
      </div>
    </div>
  );
};
